<?php

use Illuminate\Database\Capsule\Manager as DB;
use SliderCapcha\SliderCapcha;

class PublicController extends CoreController
{
    public function adminloginAction()
    {
        if (!$this->isPost()) {
            $cnf = configModel::where('type', 1)->pluck('value', 'key');
            $this->_view->assign('title',   $cnf['name']);
            $this->_view->assign('icp',     $cnf['icp']);
            $this->_view->assign('version', $cnf['version']);
            $this->_view->display('public/adminlogin.html');
        } else {
            do {
                if (!SliderCapcha::check()) {
                    $result = [
                        'ret' => 1,
                        'msg' => '滑动验证失败.',
                    ];
                    break;
                }
                $inputs = $this->postData;
                $roles  = [
                    'username' => ['role' => 'required|exists:admin.username', 'msg' => '用户名'],
                    'password' => ['role' => 'required', 'msg' => '密码'],
                ];
                Validate::check($inputs, $roles);
                $sysusers = new adminModel();
                if ($sysusers->checkUsername($inputs['username']) == FALSE) {
                    $result = [
                        'ret' => 3,
                        'msg' => '无此账号.',
                    ];
                    break;
                }
                if ($sysusers->checkStatus($inputs['username']) == FALSE) {
                    $result = [
                        'ret' => 4,
                        'msg' => '账号已锁定.',
                    ];
                    break;
                }
                if ($sysusers->checkPassword($inputs['username'], $inputs['password']) == FALSE) {
                    if (!isset($this->session->try_times)) {
                        $this->session->try_times = 0;
                    }
                    $this->session->try_times++;
                    if ($this->session->try_times > 5) {
                        $result = [
                            'ret' => 4,
                            'msg' => '账号已锁定.',
                        ];
                        $rows   = [
                            'lockuntil' => time() + 60 * 20,
                        ];
                        DB::table('admin')->where('username', '=', $inputs['username'])->update($rows);
                        setcookie('lockFlag', 1, time() + 60 * 20);
                        $this->session->del('try_times');
                    } else {
                        $result = [
                            'ret' => 5,
                            'msg' => '密码有误,剩余' . (5 - $this->session->try_times) . '次',
                        ];
                    }
                    break;
                }
                if ($data = $sysusers->setUserLogin($inputs['username'], $inputs['password'])) {
                    $this->session->del('try_times');
                    $result = [
                        'ret'  => 0,
                        'msg'  => '登陆成功.',
                        'data' => $data
                    ];
                } else {
                    $result = [
                        'ret' => 6,
                        'msg' => '登陆失败.',
                    ];
                }
            } while (FALSE);
            json($result);
        }
    }

    public function adminmakeAction()
    {
        $config['dir'] = APP_PATH . '/public/plugins/slide-capcha/bg/';
        $sc            = new SliderCapcha($config);
        $sc->make();
    }

    public function logoutAction()
    {
        $auth = new Auth(_RBACCookieKey_);
        $auth->logout();
        redirect('/public/login');
    }

    public function checkloginAction()
    {
        $lockFlag = $this->getCookie('lockFlag', 0);
        if ($lockFlag == 1) {
            $result = array(
                'ret' => 800,
                'msg' => '重试次数过多了， 20分钟后再重试吧.',
            );
            $this->session->del('try_times');
        } else {
            if (!empty($_POST)) {
                do {
                    $qaptcha_key = $this->session->qaptcha_key;
                    if (empty($qaptcha_key)) {
                        $result = array(
                            'ret' => 300,
                            'msg' => '滑动验证失败.',
                        );
                        break;
                    }

                    $username = $this->getPost('username', NULL);
                    $password = $this->getPost('password', NULL);
                    if ($username == NULL || $password == NULL) {
                        $result = array(
                            'ret' => 400,
                            'msg' => '用户名或者密码为空.',
                        );
                        break;
                    }
                    $sysusers = new adminModel();
                    if ($sysusers->checkUsername($username) == FALSE) {
                        $result = array(
                            'ret' => 500,
                            'msg' => '未找到匹配用户名.',
                        );
                        break;
                    }
                    if ($sysusers->checkPassword($username, $password) == FALSE) {
                        if (!isset($this->session->try_times)) {
                            $this->session->try_times = 0;
                        }
                        $this->session->try_times++;
                        if ($this->session->try_times > 10) {
                            $result = array(
                                'ret' => 800,
                                'msg' => '重试次数过多了， 20分钟后再重试吧.',
                            );
                            setcookie('lockFlag', 1, time() + 60 * 20);
                            $this->session->del('try_times');
                        } else {
                            $result = array(
                                'ret' => 600,
                                'msg' => '密码有误.',
                            );
                        }
                        break;
                    }
                    if ($sysusers->setUserLogin($username, $password)) {
                        $this->session->del('qaptcha_key');
                        $this->session->del('try_times');
                        $result = array(
                            'ret' => 0,
                            'msg' => '登陆成功.',
                        );
                        break;
                    } else {
                        $result = array(
                            'ret' => 100,
                            'msg' => '登陆失败.',
                        );
                        break;
                    }
                } while (FALSE);
            } else {
                $this->session->del('qaptcha_key');
                $result = array(
                    'ret' => 700,
                    'msg' => '登陆方式失效.',
                );
            }
        }
        json($result);
    }

    #[qiniuToken]
    public function uptokenAction()
    {
        // 需要填写你的 Access Key 和 Secret Key
        $cdnCfg = configModel::where('type', 4)->pluck('value', 'key');

        $accessKey = $cdnCfg['accessKey'];
        $secretKey = $cdnCfg['secretKey'];
        $bucket    = $cdnCfg['bucket'];

        // 生成上传 Token
        $token = remember('qiniuToken', 3600, function () use($accessKey, $secretKey, $bucket){
            // 构建鉴权对象
            $auth = new \Qiniu\Auth($accessKey, $secretKey);
            // 要上传的空间
            return $auth->uploadToken($bucket);
        });

        if (!$token) {
            ret(3, 'uptoken获取失败');
        } else {
            ret(0, 'uptoken', $token);
        }
    }

    private function remote_filesize($uri)
    {
        ob_start();
        $ch = curl_init($uri); // make sure we get the header
        curl_setopt($ch, CURLOPT_HEADER, 1); // make it a http HEAD request
        curl_setopt($ch, CURLOPT_NOBODY, 1); // if auth is needed, do it here
        $okay = curl_exec($ch);
        curl_close($ch); // get the output buffer
        $head = ob_get_contents(); // clean the output buffer and return to previous // buffer settings
        ob_end_clean();  // gets you the numeric value from the Content-Length // field in the http header
        $regex = '/Content-Length:\s([0-9].+?)\s/';
        preg_match($regex, $head, $matches);  // if there was a Content-Length field, its value // will now be in $matches[1]
        if (isset($matches[1])) {
            return $matches[1];
        } else {
            return 0;
        }
    }

    #[前端上传触发事件]
    public function frontenduploadAction()
    {
        $remote_url = $this->get('remote_url');
        $file_size  = $this->get('file_size');
        $cat_id     = $this->get('cat_id');
        if($file_size==0){
            $file_size = $this->remote_filesize($remote_url);
        }
        Hook::emit('file_upload_success',
            [
                'cat_id'     => $cat_id,
                'remote_url' => $remote_url,
                'file_size'  => $file_size
            ]);
        json(['ret'=>0, 'msg'=>'file upload success']);
    }

}
